package com.peacebird.ec.api.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.peacebird.ec.api.dto.ReturnT;
import com.peacebird.ec.api.dto.SecurityPbProperties;
import com.peacebird.ec.api.util.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author: ZYZ
 * @DateTime: 2020/3/6 10:19
 * @Description:
 */
@Component
public class ApiSignatureInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = LoggerFactory.getLogger(ApiSignatureInterceptor.class);

    @Autowired
    private SecurityPbProperties securityPbProperties;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        /**
         * 由于码栈限制，暂时使用简单IP白名单方式来过滤
         */
        logger.debug("**********进入权限验证**********");
        boolean isMatch = false;
        if (securityPbProperties.getIgnoreSignUri() != null) {
            Set<String> uriSet = new HashSet<>(securityPbProperties.getIgnoreSignUri());
            String requestUri = request.getRequestURI();
            for (String uri : uriSet) {
                isMatch = requestUri.contains(uri);
                if (isMatch) {
                    break;
                }
            }
        }
        if (isMatch) {
            return true;
        }

        boolean isIpMatch = false;
        if (securityPbProperties.getIp() != null) {
            //限制IP访问
            Set<String> ipSet = new HashSet<>(securityPbProperties.getIp());
            //获取IP地址
            String ipAddress = IpUtil.getIpAddr(request);

            for (String uri : ipSet) {
                isIpMatch = ipAddress.equals(uri);
                if (isIpMatch) {
                    break;
                }
            }
        }
        if (!isIpMatch) {
            logger.debug("**********非白名单IP，访问受限**********");
            response.setStatus(403);
            returnFail("非白名单IP，访问受限", response);
            return false;
        }
        logger.debug("**********IP验证通过**********");


        return true;
    }


    private void returnFail(String msg, ServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        String result = JSONObject.toJSONString(new ReturnT<String>(403,msg));
        out.println(result);
        out.flush();
        out.close();
    }

}
